package cyou.breathe.yuque;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import cyou.breathe.constant.Constant;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MarkdownDownloader {

    private static final HttpClient CLIENT = HttpClient.newHttpClient();
    private static final Pattern IMAGE_PATTERN = Pattern.compile("!\\[[^\\]]*]\\((https?://[^)]+)\\)");
    public static void savePage(String bookId, String slug, Path path, String cookie) {
        try {
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(String.format(Constant.GET_DOC_MESSAGE, slug, bookId)))
                    .timeout(Duration.ofMinutes(2))
                    .header("Cookie", cookie)
                    .GET()
                    .build();
            HttpResponse<String> response = CLIENT.send(request, HttpResponse.BodyHandlers.ofString());

            assert response.statusCode() == 200 : "下载失败: " + slug + ", status=" + response.statusCode();

            JsonNode data = new ObjectMapper().readTree(response.body()).path("data");
            String markdown = data.path("sourcecode").asText();
            // 💡 下载图片并替换 Markdown 中的链接
            String updatedMarkdown = downloadAndReplaceImages(markdown, Paths.get("download", "appendix"), path.getParent());
            Files.createDirectories(path.getParent());
            Files.writeString(path, updatedMarkdown, StandardCharsets.UTF_8);
            System.out.println("保存页面成功: " + path);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("保存页面失败: " + slug + ", 错误: " + e.getMessage());
        }
    }

    private static String downloadAndReplaceImages(String markdown, Path imageDir, Path markdownDir) throws IOException, InterruptedException {
        Matcher matcher = IMAGE_PATTERN.matcher(markdown);
        StringBuffer result = new StringBuffer();

        while (matcher.find()) {
            String imageUrl = matcher.group(1);
            String extension = getFileExtension(imageUrl);
            String fileName = UUID.randomUUID() + extension;
            Files.createDirectories(Path.of(YuqueService.imageOutputDir));
            Path localImagePath = imageDir.resolve(YuqueService.imageOutputDir + fileName);
            System.out.println("localImagePath = " + localImagePath);
            try {
                HttpRequest imgRequest = HttpRequest.newBuilder()
                        .uri(URI.create(imageUrl))
                        .timeout(Duration.ofSeconds(30))
                        .GET()
                        .build();
                HttpResponse<byte[]> imgResponse = CLIENT.send(imgRequest, HttpResponse.BodyHandlers.ofByteArray());
                System.out.println("图片下载成功");
                if (imgResponse.statusCode() == 200) {
                    System.out.println("图片开始保存");
                    Files.write(localImagePath, imgResponse.body());
                    System.out.println("图片保存成功");
                    //把所有的图片下载的图片放到D:\\yuque\\breathe\\
                    String newImageMarkdown = "![[" + fileName + "]]";
                    matcher.appendReplacement(result, Matcher.quoteReplacement(newImageMarkdown));
                } else {
                    System.err.println("图片下载失败: " + imageUrl + ", 状态码: " + imgResponse.statusCode());
                    // 保留原样
                    matcher.appendReplacement(result, matcher.group());
                }
            } catch (Exception e) {
                System.err.println("图片下载或保存异常: " + imageUrl + ", 错误: " + e.getMessage());
                // 保留原样
                matcher.appendReplacement(result, matcher.group());
            }
        }

        matcher.appendTail(result);
        return result.toString();
    }


    private static String getFileExtension(String url) {
        int queryIdx = url.indexOf('?');
        if (queryIdx != -1) {
            url = url.substring(0, queryIdx);
        }
        int dotIdx = url.lastIndexOf('.');
        if (dotIdx != -1 && dotIdx > url.lastIndexOf('/')) {
            return url.substring(dotIdx);
        }
        return ".png";
    }
}
